package cn.openea.perpartner.componet.web.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.cglib.CglibUtil;
import cn.openea.perpartner.common.core.manager.AsyncManager;
import cn.openea.perpartner.componet.web.entity.HisMsg;
import cn.openea.perpartner.componet.web.entity.InsMsg;
import cn.openea.perpartner.componet.web.mapper.HisMsgMapper;
import cn.openea.perpartner.componet.web.service.IHisMsgService;
import cn.openea.perpartner.componet.web.service.ITemplateMsgService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.TimerTask;

/**
 * @author Weird077
 * @description TODO
 * @date 2023-03-13 10:47
 */
@Slf4j
@Service
public class HisMsgServiceImpl extends ServiceImpl<HisMsgMapper, HisMsg> implements IHisMsgService {
    @Autowired
    private ITemplateMsgService templateMsgService;

    @Scheduled(cron = "${meily.scheduled.default.cron}")
    @Transactional(rollbackFor = {RuntimeException.class, Exception.class})
    public void migrateData() {
        AsyncManager.me().execute(new TimerTask() {
            @Override
            public void run() {
                LambdaQueryWrapper<InsMsg> wrapper = new LambdaQueryWrapper<>();
                Date lastDate = DateUtil.offsetMonth(DateUtil.date(), -1);
                wrapper.le(InsMsg::getCreateTime, DateUtil.format(lastDate, "yyyy-MM-dd HH:mm:ss"));
                List<InsMsg> insMsgList = templateMsgService.list(wrapper);
                if (!insMsgList.isEmpty()) {
                    List<HisMsg> hisMsgList = CglibUtil.copyList(insMsgList, HisMsg::new);
                    //迁移到历史表
                    saveBatch(hisMsgList);
                    //删除热点数据
                    templateMsgService.removeBatchByIds(insMsgList);
                }
            }
        });
    }
}
